<template>
  <div class="register-container">
    <div class="register-box">
      <!-- 添加导航栏 -->
      <van-nav-bar 
        title="用户注册" 
        left-arrow 
        @click-left="goBack"
      />
      
      <van-form ref="formRef" @submit="handleRegister" class="register-form">
        <!-- 成功提示 -->
        <div v-if="showSuccess" class="message-success">
          <van-icon name="success" class="success-icon" />
          <span>注册成功，正在跳转到登录页面...</span>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="formError" class="form-error">
          <van-icon name="warning" class="error-icon" />
          <span>{{ formError }}</span>
        </div>
        
        <van-field
          v-model="registerForm.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="registerRules.username"
        />
        
        <van-field
          v-model="registerForm.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="registerRules.password"
        />
        
        <van-field
          v-model="registerForm.confirmPassword"
          type="password"
          name="confirmPassword"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="registerRules.confirmPassword"
        />
        
        <van-field
          v-model="registerForm.email"
          name="email"
          label="邮箱"
          placeholder="请输入邮箱"
          :rules="registerRules.email"
        />
        
        <van-field
          v-model="registerForm.phoneNumber"
          name="phoneNumber"
          label="手机号"
          placeholder="请输入手机号（选填）"
          :rules="registerRules.phoneNumber"
        />
        
        <van-checkbox v-model="agreeProtocol" shape="square">
          同意用户协议、隐私政策和服务条款
        </van-checkbox>
        
        <div class="register-btn-wrapper">
          <van-button 
            round 
            block 
            type="primary" 
            native-type="submit"
            class="register-btn"
            :loading="loading"
            :disabled="!agreeProtocol"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </van-button>
        </div>
        
        <div class="login-link-wrapper">
          <router-link to="/login" class="login-link">
            已有账号？去登录
          </router-link>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { register } from '@/api/index.js';

const router = useRouter();
const formRef = ref(null);
const loading = ref(false);
const agreeProtocol = ref(false);

// 新增：提示状态
const showSuccess = ref(false);
const formError = ref('');

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phoneNumber: ''
});

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'onBlur' },
    { min: 3, max: 16, message: '用户名长度为3-16位', trigger: 'onBlur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'onBlur' },
    { 
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/, 
      message: '密码需6-16位，且包含字母和数字', 
      trigger: 'onBlur' 
    },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'onBlur' },
    {
      validator: (value) => {
        return value === registerForm.password;
      },
      message: '两次输入的密码不一致',
      trigger: 'onBlur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'onBlur' },
    { 
      type: 'email', 
      message: '请输入正确的邮箱格式', 
      trigger: 'onBlur' 
    },
  ],
  phoneNumber: [
    {
      validator: (value) => {
        if (!value) return true;
        return /^1[3-9]\d{9}$/.test(value);
      },
      message: '请输入正确的手机号格式',
      trigger: 'onBlur',
    },
  ],
};

// 返回登录页面
const goBack = () => {
  router.push('/login');
};

const handleRegister = async () => {
  // 清空之前的提示
  showSuccess.value = false;
  formError.value = '';
  
  try {
    loading.value = true;
    
    if (registerForm.password !== registerForm.confirmPassword) {
      formError.value = '两次输入的密码不一致';
      loading.value = false;
      return;
    }
    
    const submitData = { 
      username: registerForm.username,
      password: registerForm.password,
      email: registerForm.email
    };
    
    if (registerForm.phoneNumber && registerForm.phoneNumber.trim() !== '') {
      submitData.phoneNumber = registerForm.phoneNumber;
    }
    
    const res = await register(submitData);
    
    if (res === null) {
      console.error('后端返回数据为null，注册失败');
      formError.value = '注册失败，请稍后重试';
      return;
    }
    
    if (res) {
      // 显示成功提示
      showSuccess.value = true;
      
      // 清空表单
      Object.keys(registerForm).forEach(key => {
        registerForm[key] = '';
      });
      agreeProtocol.value = false;
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/login');
      }, 2000);
    } else {
      formError.value = res.message || '注册失败';
    }
  } catch (error) {
    console.error('注册请求失败:', error);
    formError.value = '网络错误，请稍后重试';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.register-box {
  width: 100%;
  max-width: 350px;
  background-color: #fff;
  border-radius: 8px;
  padding: 0; /* 移除内边距，因为导航栏会占据顶部 */
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden; /* 确保圆角效果 */
}

/* 移除原来的标题栏 */
.title-bar {
  display: none;
}

.register-form {
  padding: 20px; /* 表单内容添加内边距 */
}

.van-field {
  margin-bottom: 15px;
}

.van-checkbox {
  margin: 10px 0;
  font-size: 14px;
  color: #666;
}

.register-btn-wrapper {
  margin: 25px 0 15px 0;
}

.register-btn {
  height: 42px;
  font-size: 16px;
  background-color: #66b3ff;
  border-color: #66b3ff;
}

.register-btn:disabled {
  background-color: #b3d9ff;
  border-color: #b3d9ff;
}

.login-link-wrapper {
  text-align: center;
  margin-top: 10px;
}

.login-link {
  font-size: 14px;
  color: #66b3ff;
  text-decoration: none;
}

.login-link:hover {
  text-decoration: underline;
}

/* 错误提示样式 */
.form-error {
  display: flex;
  align-items: center;
  color: #f53f3f;
  font-size: 14px;
  padding: 10px;
  margin-bottom: 15px;
  background-color: #fff2f0;
  border-radius: 6px;
  border-left: 3px solid #f53f3f;
  
  .error-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}

/* 成功提示样式 */
.message-success {
  display: flex;
  align-items: center;
  color: #07c160;
  font-size: 14px;
  padding: 10px;
  margin-bottom: 15px;
  background-color: #f0fff8;
  border-radius: 6px;
  border-left: 3px solid #07c160;
  
  .success-icon {
    margin-right: 8px;
    font-size: 16px;
  }
}
</style>